<template>
  <div class="product-management">
    <!-- 搜索区域 -->
    <a-row :gutter="16" class="search-row">
      <a-col :span="8">
        <a-input
            v-model="id"
            placeholder="请输入商品编号"
            addon-before="商品编号" class="search-input"/>
      </a-col>
      <a-col :span="8">
        <a-input
            v-model="name"
            placeholder="请输入商品名称"
            addon-before="商品名称" class="search-input"/>
      </a-col>
    </a-row>

    <!-- 查询和重置按钮 -->
    <a-row :gutter="16" class="button-row">
      <a-col :span="12">
        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-button class="reset-btn" @click="handleReset">重置</a-button>
      </a-col>
    </a-row>

    <!-- Tab栏 -->
    <a-tabs :active-key="defaultActiveKey" @change="handleChange" class="tabs">
      <a-tab-pane key="all" :tab="`全部（${allCount} ）`"></a-tab-pane>
      <a-tab-pane key="grounding" :tab="`上架（${sellingCount} ）`"></a-tab-pane>
      <a-tab-pane key="undercarriage" :tab="`下架（${alertCount} ）`"></a-tab-pane>
    </a-tabs>

    <!-- 表格区域 -->
    <a-table :data-source="filteredData" :columns="columns" rowKey="key" class="product-table"
             :scroll="{ x: 'max-content' }">
      <!-- 商品信息列 -->
      <template slot="images" slot-scope="text, record">
        <a-avatar :src="record.image" shape="square" class="product-image"/>
        <span style="margin: 0px 5px;"></span>
        <span slot="name">{{ record.name }}</span>
      </template>

      <!-- 状态列 -->
      <template slot="status" slot-scope="text, record">
        <span v-if="record && record.status !== undefined && record.status !== null"
              :style="{color:
                       record.status === '上架' ? '#52c41a' :
                       record.status === '下架' ? '#ff4d4f' :
                        '#000000',
                background:  record.status === '下架'? '#fef0f0': '#F0F9EB',
                padding: '5px 10px'
              }">
          {{ record.status }}
        </span>
      </template>

      <!-- 状态列 -->
      <template slot="specType" slot-scope="text, record">
        <span v-if="record && record.specType !== undefined && record.status !== null"
              :style="{color:
                       record.specType === '多规格' ? '#67c23a' :
                       record.specType === '单规格' ? '#ff4d4f' :
                       '#000000',
                background: record.specType === '单规格' ? '#fef0f0':'#f0f9eb',
                padding: '5px 10px'
              }">
          {{ record.specType }}
        </span>
      </template>

      <!-- 操作列 -->
      <template slot="action" slot-scope="text, record" class="handle-list">
        <a-space>
          <a-button type="link" style="padding: 0px;" @click="handleDetail(record)" class="action-btn">详情</a-button>
          <a-button type="link" style="padding: 0px;" @click="handleEdit(record)" class="action-btn">编辑</a-button>
          <a-button v-if="record.status === '上架'" type="link" style="padding: 0px;" @click="handleShelfIn(record)"
                    class="action-btn">下架
          </a-button>
          <a-button v-if="record.status === '下架'" type="link" style="padding: 0px;" @click="PutaWayShelfIn(record)"
                    class="action-btn">上架
          </a-button>
          <a-button type="link" style="padding: 0px; color: red;" danger @click="handleDelete(record)"
                    class="action-btn">删除
          </a-button>
        </a-space>
      </template>
    </a-table>
    <!-- 详情模态框 -->
    <a-modal
        :visible="detailModalVisible"
        title="商品详情"
        @ok="handleDetailCancel"
        @cancel="handleDetailCancel"
        id="a-modal"
    >
      <a-avatar :src="currentRecord.image" shape="square" style="width: 100px;height: 100px;"/>
      <a-input v-model="currentRecord.id"
               addon-before="商品编号"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-model="currentRecord.name"
               addon-before="商品名称"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-model="currentRecord.content"
               addon-before="商品描述"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-model="currentRecord.lineationPrice"
               addon-before="划线价格"
               :class="['search-input',['mb-16']]" disabled/>
      <a-input v-model="currentRecord.price"
               addon-before="价格"
               :class="['search-input',['mb-16']]" disabled/>
      <a-input v-model="currentRecord.status"
               addon-before="上架状态"
               :class="['search-input',['mb-16']]" disabled/>
      <a-input v-model="currentRecord.specType"
               addon-before="规格状态"
               :class="['search-input',['mb-16']]" disabled/>
    </a-modal>

    <!-- 编辑模态框 -->
    <a-modal
        :visible="editModalVisible"
        title="编辑商品"
        @ok="handleEditCancel"
        @cancel="handleEditCancel"
    >
      <a-avatar :src="currentRecord.image" shape="square" style="width: 100px; height: 100px;"/>
      <a-input v-model="currentRecord.id"
               addon-before="商品编号"
               :class="['search-input','mb-16']"/>
      <a-input v-model="currentRecord.name"
               addon-before="商品名称"
               :class="['search-input','mb-16']"/>
      <a-input v-model="currentRecord.content"
               addon-before="商品描述"
               :class="['search-input','mb-16']"/>
      <a-input v-model="currentRecord.lineationPrice"
               addon-before="划线价格"
               :class="['search-input',['mb-16']]"/>
      <a-input v-model="currentRecord.price"
               addon-before="价格"
               :class="['search-input',['mb-16']]"/>
      <a-input v-model="currentRecord.status"
               addon-before="上架状态"
               :class="['search-input',['mb-16']]"/>
      <a-input v-model="currentRecord.specType"
               addon-before="规格状态"
               :class="['search-input',['mb-16']]"/>
    </a-modal>

    <!-- 下架模态框 -->
    <a-modal
        :visible="shelfInModalVisible"
        title="商品下架"
        @ok="handleShelfInOk"
        @cancel="handleShelfInCancel"
    >
      <p>确认要将该商品下架吗？</p>
    </a-modal>

    <!-- 上架模态框 -->
    <a-modal
        :visible="PutaWayShelfInVisible"
        title="商品上架"
        @ok="PutaWayShelfInOk"
        @cancel="PutaWayShelfInCancel"
    >
      <p>确认要将该商品上架吗？</p>
    </a-modal>

    <!-- 删除确认模态框 -->
    <a-modal
        :visible="deleteModalVisible"
        title="确认删除"
        @ok="handleDeleteConfirm"
        @cancel="handleDeleteCancel"
    >
      <p>确认要删除该商品吗？</p>
    </a-modal>
  </div>
</template>

<script>
import {Avatar, Modal} from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import {METHOD, request} from "@/utils/request";

export default {
  components: {
    'a-avatar': Avatar,
    'a-modal': Modal,
  },
  data() {
    return {
      id: '',
      content: '',
      name: '',
      lineationPrice: '',
      price: '',
      amount: '',
      status: '',
      specType: '',
      images: '',
      description: '',
      category: '',
      defaultActiveKey: 'all',
      allCount: 0,
      sellingCount: 0,
      alertCount: 0,
      allData: [

      ],
      filteredData: [],  // 用于展示的过滤后的数据
      detailModalVisible: false,  // 控制详情模态框的显示/隐藏
      editModalVisible: false,    // 控制编辑模态框的显示/隐藏
      shelfInModalVisible: false, // 控制下架模态框的显示/隐藏
      PutaWayShelfInVisible: false, // 控制上架模态框的显示/隐藏
      deleteModalVisible: false,  // 控制删除确认模态框的显示/隐藏
      currentRecord: {},        // 当前操作的商品记录
      columns: [
        {
          title: '商品编号',
          dataIndex: 'id',
          key: 'id',
          width: 100,
        },
        {
          title: '商品信息',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: {customRender: 'images'},
          width: 300,
        },
        {
          title: '商品描述',
          dataIndex: 'content',
          key: 'content',
          width: 300,
        },
        {
          title: '划线价格',
          dataIndex: 'lineationPrice',
          key: 'lineationPrice',
          width: 100,
        },
        {
          title: '价格',
          dataIndex: 'price',
          key: 'price',
          width: 100,
        },
        {
          title: '商品状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: {customRender: 'status'},
          width: 100,
        },
        {
          title: '规格状态',
          dataIndex: 'specType',
          key: 'specType',
          scopedSlots: {customRender: 'specType'},
          width: 130,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 180, // 确保给创建时间列足够宽度
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          width: 180, // 同样给修改时间列足够宽度
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: {customRender: 'action'},
          fixed: 'right',
          width: 150,
        }
      ],
    };
  },
  watch: {
    // 当 `allData` 发生变化时，重新过滤数据
    allData: 'filterData',
  },
  mounted() {
    this.filterData();  // 页面加载时初始化数据
    this.fetchData();  // 调用 fetchData 获取数据// 检查 allData 的内容
  },
  methods: {
    validateAmount(event) {
      let value = event.target.value;

      // 使用正则表达式检查是否为数字
      if (!/^\d*$/.test(value)) {
        this.showError = true;
        this.$nextTick(() => {
          this.currentRecord.amount = this.currentRecord.amount.replace(/\D/g, '');
        });
      } else {
        this.showError = false;
      }
    },
    // 查询按钮
    handleSearch() {
      this.filterData();
    },
    // 重置按钮
    handleReset() {
      this.id = '';
      this.name = '';
      this.category = '';
      this.defaultActiveKey = 'all'; // 重置时默认显示全部
      this.filterData(); // 重置时显示所有数据
    },
    // Tab切换
    handleChange(activeKey) {
      this.defaultActiveKey = activeKey;
      this.filterData(); // 切换Tab时重新过滤数据
    },
    // 过滤数据
    filterData() {
      let filtered = [...this.allData]; // 从 allData 复制数据以避免直接修改原始数据

      // 循环所有的列并根据列的dataIndex值进行过滤
      this.columns.forEach((column) => {
        // 判断当前列是否需要过滤（例如：'id', 'name', 'price'等）
        if (this[column.dataIndex]) {
          filtered = filtered.filter(item => {
            // 例如: 根据商品编号
            if (column.dataIndex === 'id' && this[column.dataIndex]) {
              return item.id.includes(this[column.dataIndex]);
            }
            // 根据商品描述
            if (column.dataIndex === 'content' && this[column.dataIndex]) {
              return item.content.includes(this[column.dataIndex]);
            }
            // 根据商品名称
            if (column.dataIndex === 'name' && this[column.dataIndex]) {
              return item.name.includes(this[column.dataIndex]);
            }
            // 根据价格
            if (column.dataIndex === 'price' && this[column.dataIndex]) {
              return item.price.includes(this[column.dataIndex]);
            }
            // 根据商品状态
            if (column.dataIndex === 'status' && this[column.dataIndex]) {
              return item.status.includes(this[column.dataIndex]);
            }
            // 根据规格状态
            if (column.dataIndex === 'specType' && this[column.dataIndex]) {
              return item.specType.includes(this[column.dataIndex]);
            }
            // 根据创建时间
            if (column.dataIndex === 'createTime' && this[column.dataIndex]) {
              return item.createTime.includes(this[column.dataIndex]);
            }
            // 根据修改时间
            if (column.dataIndex === 'updateTime' && this[column.dataIndex]) {
              return item.updateTime.includes(this[column.dataIndex]);
            }
            return true;
          });
        }
      });

      // 进一步根据 Tab 进行过滤
      switch (this.defaultActiveKey) {
        case 'all':
          break;
        case 'grounding':
          filtered = filtered.filter(item => item.status === '上架');
          break;
        case 'undercarriage':
          filtered = filtered.filter(item => item.status === '下架');
          break;
        default:
          break;
      }

      // 更新过滤后的数据
      this.filteredData = filtered;
      this.updateCounts();  // 更新 Tab 页统计数据
    },
    // 更新各 Tab 页的统计数
    updateCounts() {
      this.allCount = this.filteredData.length;
      this.sellingCount = this.filteredData.filter(item => item.status === '上架').length;
      this.alertCount = this.filteredData.filter(item => item.status === '下架').length;
    },
    // 打开详情模态框
    handleDetail(record) {
      console.log('Detail Record:', record);
      if (record) {
        this.currentRecord = record;
        console.log('Current Record:', this.currentRecord); // 打印 currentRecord 以检查值
      } else {
        console.warn('No record provided');
      }
      // 打开模态框
      this.detailModalVisible = true;
    },

    // 关闭详情模态框
    handleDetailCancel() {
      this.detailModalVisible = false;
    },

    // 打开编辑模态框
    handleEdit(record) {
      this.currentRecord = record;
      this.editModalVisible = true;
    },

    // 关闭编辑模态框
    handleEditCancel() {
      this.editModalVisible = false;
    },

    // 打开下架模态框
    PutaWayShelfIn(record) {
      this.currentRecord = record;
      this.PutaWayShelfInVisible = true;
    },

    // 关闭下架模态框
    PutaWayShelfInOk() {
      try {
        // 调用后端 API 获取用户信息
        request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/goods/updateGoodsStatus?id=` + this.currentRecord.id + `&status=0`,
            METHOD.POST
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        ).then(() => {
          // 在状态更新后调用刷新数据的 API
          this.fetchData();
        }).catch(error => {
          console.error(error);
        });
      } catch (error) {
        console.error(error);
      }
      this.PutaWayShelfInVisible = false;
    },

    // 关闭下架模态框
    PutaWayShelfInCancel() {
      this.PutaWayShelfInVisible = false;
    },

    // 打开下架模态框
    handleShelfIn(record) {
      this.currentRecord = record;
      this.shelfInModalVisible = true;
    },

    // 关闭下架模态框
    handleShelfInOk() {
      try {
        // 调用后端 API 获取用户信息
        request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/goods/updateGoodsStatus?id=` + this.currentRecord.id + `&status=1`,
            METHOD.POST
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        ).then(() => {
          // 在状态更新后调用刷新数据的 API
          this.fetchData();
        }).catch(error => {
          console.error(error);
        });
      } catch (error) {
        console.error(error);
      }
      this.shelfInModalVisible = false;
    },

    // 关闭下架模态框
    handleShelfInCancel() {
      this.shelfInModalVisible = false;
    },

    // 打开删除确认模态框
    handleDelete(record) {
      this.currentRecord = record;
      this.deleteModalVisible = true;
    },

    // 确认删除
    handleDeleteConfirm() {
      console.log('已确认删除:', this.currentRecord);
      // 在这里编写实际的删除逻辑，比如调用API等
      this.deleteModalVisible = false;
    },

    // 取消删除
    handleDeleteCancel() {
      this.deleteModalVisible = false;
    },

    async fetchData() {
      try {
        // 调用后端 API 获取用户信息
        const response = await request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/goods/infoAllGoods`,
            METHOD.GET
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        );
        this.allData = response.data.data;
        this.filteredData = this.allData;  // 初始时过滤数据为全部数据
        return response.data.data;
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.search-row {
  margin-bottom: 20px;
}

.search-input, .search-select {
  width: 100%;
}

.button-row {
  margin-top: 16px;
}

.reset-btn {
  margin-left: 8px;
}

.tabs {
  margin-top: 20px;
  background-color: whitesmoke;
  border-radius: 8px;
}

.product-table {
  background-color: whitesmoke;
  margin-top: 16px;
  max-width: 100%;
  overflow-x: auto;
}

.product-image {
  width: 50px;
  height: 50px;
}

.action-btn {
  color: #1890ff;
}

.action-btn:hover {
  color: #40a9ff;
}

.mb-16 {
  margin-bottom: 16px;
}
</style>